#!/usr/bin/env python3
"""
S3 Bucket Delete Tool - DeleteBucket API 演示工具

这个工具演示如何使用 DeleteBucket API 删除存储桶。

使用示例:
    python s3_bucket_delete.py --name my-bucket
    python s3_bucket_delete.py --name my-bucket --force
    python s3_bucket_delete.py --prefix temp- --confirm
    python s3_bucket_delete.py --format json
    python s3_bucket_delete.py --verbose
"""

import argparse
import boto3
import json
import sys
from datetime import datetime, timezone
from botocore.config import Config
from botocore.exceptions import ClientError, NoCredentialsError


class BucketDeleteClient:
    """S3 桶删除客户端"""
    
    def __init__(self, endpoint_url='http://localhost:8000', 
                 access_key='AKIAIOSFODNN7EXAMPLE', 
                 secret_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
                 region='us-east-1'):
        """
        初始化桶删除客户端
        
        Args:
            endpoint_url: S3 服务端点
            access_key: AWS Access Key
            secret_key: AWS Secret Key
            region: AWS 区域
        """
        self.endpoint_url = endpoint_url
        self.access_key = access_key
        self.secret_key = secret_key
        self.region = region
        self._client = None
    
    def _get_client(self):
        """获取 S3 客户端"""
        if self._client is None:
            self._client = boto3.client(
                's3',
                endpoint_url=self.endpoint_url,
                aws_access_key_id=self.access_key,
                aws_secret_access_key=self.secret_key,
                region_name=self.region,
                config=Config(s3={'addressing_style': 'path'})
            )
        return self._client


    def _check_bucket_empty(self, bucket_name):
        """检查桶是否为空"""
        try:
            s3_client = self._get_client()
            
            # 检查普通对象
            response = s3_client.list_objects_v2(Bucket=bucket_name, MaxKeys=1)
            if 'Contents' in response:
                return False, f"桶中有 {response.get('KeyCount', 0)} 个对象"
            
            # 检查未完成的分片上传
            response = s3_client.list_multipart_uploads(Bucket=bucket_name)
            if 'Uploads' in response and len(response['Uploads']) > 0:
                return False, f"桶中有 {len(response['Uploads'])} 个未完成的分片上传"
            
            return True, "桶为空"
            
        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchBucket':
                return True, "桶不存在"
            else:
                return False, f"检查失败: {e.response['Error']['Message']}"
        except Exception as e:
            return False, f"检查失败: {e}"


    def _empty_bucket(self, bucket_name):
        """清空桶内容"""
        try:
            s3_client = self._get_client()
            deleted_objects = 0
            deleted_uploads = 0
            
            print(f"🧹 正在清空桶: {bucket_name}")
            
            # 删除所有对象
            while True:
                response = s3_client.list_objects_v2(Bucket=bucket_name, MaxKeys=1000)
                
                if 'Contents' not in response:
                    break
                
                # 准备删除对象列表
                objects_to_delete = [{'Key': obj['Key']} for obj in response['Contents']]
                
                # 批量删除对象
                delete_response = s3_client.delete_objects(
                    Bucket=bucket_name,
                    Delete={'Objects': objects_to_delete}
                )
                
                deleted_count = len(delete_response.get('Deleted', []))
                deleted_objects += deleted_count
                print(f"   🗑️  已删除 {deleted_count} 个对象")
                
                # 如果没有更多对象，退出循环
                if not response.get('IsTruncated', False):
                    break
            
            # 取消所有未完成的分片上传
            response = s3_client.list_multipart_uploads(Bucket=bucket_name)
            if 'Uploads' in response:
                for upload in response['Uploads']:
                    s3_client.abort_multipart_upload(
                        Bucket=bucket_name,
                        Key=upload['Key'],
                        UploadId=upload['UploadId']
                    )
                    deleted_uploads += 1
                    print(f"   ❌ 已取消分片上传: {upload['Key']}")
            
            print(f"✅ 桶清空完成:")
            print(f"   删除对象: {deleted_objects} 个")
            print(f"   取消上传: {deleted_uploads} 个")
            
            return True, deleted_objects, deleted_uploads
            
        except Exception as e:
            print(f"❌ 清空桶失败: {e}")
            return False, 0, 0


    def delete_single_bucket(self, bucket_name, force=False, dry_run=False):
        """简单格式删除单个桶"""
        try:
            s3_client = self._get_client()
            print(f"🗑️  准备删除桶: {bucket_name}")
            
            # 检查桶是否存在
            try:
                s3_client.head_bucket(Bucket=bucket_name)
            except ClientError as e:
                if e.response['Error']['Code'] == 'NoSuchBucket':
                    print(f"⚠️  桶不存在: {bucket_name}")
                    return True
                else:
                    raise
            
            # 检查桶是否为空
            is_empty, message = self._check_bucket_empty(bucket_name)
            print(f"   📋 状态检查: {message}")
            
            if not is_empty and not force:
                print(f"❌ 桶不为空，无法删除。使用 --force 选项强制删除")
                return False
            
            if dry_run:
                print(f"🔍 模拟运行: 将删除桶 {bucket_name}")
                if not is_empty:
                    print(f"   注意: 需要先清空桶内容")
                return True
            
            # 如果桶不为空且设置了强制删除，先清空桶
            if not is_empty and force:
                success, _, _ = self._empty_bucket(bucket_name)
                if not success:
                    return False
            
            # 删除桶
            s3_client.delete_bucket(Bucket=bucket_name)
            print(f"✅ 桶删除成功: {bucket_name}")
            
            return True
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                print(f"⚠️  桶不存在: {bucket_name}")
                return True
            elif error_code == 'BucketNotEmpty':
                print(f"❌ 桶不为空: {bucket_name} - 使用 --force 选项强制删除")
                return False
            else:
                print(f"❌ 删除失败 [{error_code}]: {error_msg}")
                return False
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return False
        except Exception as e:
            print(f"❌ 未知错误: {e}")
            return False
    
    def delete_single_bucket_verbose(self, bucket_name, force=False, dry_run=False):
        """详细格式删除单个桶"""
        try:
            s3_client = self._get_client()
            print("🗑️  桶删除详细信息:")
            print("=" * 50)
            print(f"   🗂️  桶名称: {bucket_name}")
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 操作时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print(f"   ⚡ 强制模式: {'是' if force else '否'}")
            print(f"   🔍 模拟运行: {'是' if dry_run else '否'}")
            print()
            
            # 检查桶是否存在
            try:
                s3_client.head_bucket(Bucket=bucket_name)
                print(f"   ✅ 桶存在确认")
            except ClientError as e:
                if e.response['Error']['Code'] == 'NoSuchBucket':
                    print(f"   ⚠️  桶不存在: {bucket_name}")
                    return True
                else:
                    raise
            
            # 检查桶是否为空
            is_empty, message = self._check_bucket_empty(bucket_name)
            print(f"   📋 状态检查: {message}")
            
            if not is_empty and not force:
                print(f"   ❌ 桶不为空，无法删除")
                print(f"   💡 建议: 使用 --force 选项强制删除")
                return False
            
            if dry_run:
                print(f"   🔍 模拟运行: 将删除桶 {bucket_name}")
                if not is_empty:
                    print(f"   ⚠️  注意: 需要先清空桶内容")
                return True
            
            # 如果桶不为空且设置了强制删除，先清空桶
            if not is_empty and force:
                print(f"   🧹 开始清空桶内容...")
                success, deleted_objects, deleted_uploads = self._empty_bucket(bucket_name)
                if not success:
                    print(f"   ❌ 清空桶失败")
                    return False
                print(f"   ✅ 桶清空完成")
            
            # 删除桶
            print(f"   🗑️  正在删除桶...")
            s3_client.delete_bucket(Bucket=bucket_name)
            print(f"   ✅ 桶删除成功")
            print(f"   📊 操作完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            return True
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            print(f"   ❌ 删除失败:")
            print(f"      错误代码: {error_code}")
            print(f"      错误信息: {error_msg}")
            
            if error_code == 'NoSuchBucket':
                print(f"   ⚠️  桶不存在: {bucket_name}")
                return True
            elif error_code == 'BucketNotEmpty':
                print(f"   ❌ 桶不为空: {bucket_name}")
                return False
            else:
                return False
        except NoCredentialsError:
            print("   ❌ 错误: 未找到 AWS 凭据")
            return False
        except Exception as e:
            print(f"   ❌ 未知错误: {e}")
            return False
    
    def delete_single_bucket_json(self, bucket_name, force=False, dry_run=False):
        """JSON 格式删除单个桶"""
        try:
            s3_client = self._get_client()
            
            # 检查桶是否存在
            try:
                s3_client.head_bucket(Bucket=bucket_name)
                bucket_exists = True
            except ClientError as e:
                if e.response['Error']['Code'] == 'NoSuchBucket':
                    result = {
                        "success": True,
                        "bucket_name": bucket_name,
                        "status": "not_exists",
                        "message": "桶不存在"
                    }
                    print(json.dumps(result, indent=2, ensure_ascii=False))
                    return True
                else:
                    raise
            
            # 检查桶是否为空
            is_empty, message = self._check_bucket_empty(bucket_name)
            
            if not is_empty and not force:
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "error": "bucket_not_empty",
                    "error_message": "桶不为空，无法删除。使用 --force 选项强制删除",
                    "bucket_status": message
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return False
            
            if dry_run:
                result = {
                    "success": True,
                    "bucket_name": bucket_name,
                    "operation": "dry_run",
                    "would_delete": True,
                    "bucket_status": message,
                    "requires_emptying": not is_empty
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return True
            
            # 如果桶不为空且设置了强制删除，先清空桶
            deleted_objects = 0
            deleted_uploads = 0
            if not is_empty and force:
                success, deleted_objects, deleted_uploads = self._empty_bucket(bucket_name)
                if not success:
                    result = {
                        "success": False,
                        "bucket_name": bucket_name,
                        "error": "empty_failed",
                        "error_message": "清空桶失败"
                    }
                    print(json.dumps(result, indent=2, ensure_ascii=False))
                    return False
            
            # 删除桶
            s3_client.delete_bucket(Bucket=bucket_name)
            result = {
                "success": True,
                "bucket_name": bucket_name,
                "operation": "delete",
                "deleted_objects": deleted_objects,
                "deleted_uploads": deleted_uploads,
                "deletion_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return True
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                result = {
                    "success": True,
                    "bucket_name": bucket_name,
                    "status": "not_exists",
                    "message": "桶不存在"
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return True
            else:
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "error": error_code,
                    "error_message": error_msg
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return False
        except NoCredentialsError:
            result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据"
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False
        except Exception as e:
            result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e)
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False


    def delete_buckets_by_prefix(self, prefix, confirm=False, dry_run=False):
        """简单格式按前缀批量删除桶"""
        try:
            s3_client = self._get_client()
            
            # 列出所有桶
            response = s3_client.list_buckets()
            buckets = response['Buckets']
            
            # 过滤匹配前缀的桶
            matching_buckets = [b['Name'] for b in buckets if b['Name'].startswith(prefix)]
            
            if not matching_buckets:
                print(f"📭 没有找到前缀为 '{prefix}' 的桶")
                return True
            
            print(f"🔍 找到 {len(matching_buckets)} 个匹配的桶:")
            for bucket_name in matching_buckets:
                print(f"   • {bucket_name}")
            
            if not confirm and not dry_run:
                print(f"\n⚠️  这将删除 {len(matching_buckets)} 个桶！")
                print(f"请使用 --confirm 选项确认删除")
                return False
            
            if dry_run:
                print(f"\n🔍 模拟运行: 将删除 {len(matching_buckets)} 个桶")
                return True
            
            # 批量删除
            success_count = 0
            failed_buckets = []
            
            print(f"\n🗑️  开始批量删除:")
            print("-" * 50)
            
            for bucket_name in matching_buckets:
                if self.delete_single_bucket_simple(bucket_name, force=True):
                    success_count += 1
                else:
                    failed_buckets.append(bucket_name)
                print()
            
            # 显示结果
            print("📊 批量删除结果:")
            print(f"   ✅ 成功: {success_count}/{len(matching_buckets)}")
            print(f"   ❌ 失败: {len(failed_buckets)}/{len(matching_buckets)}")
            
            if failed_buckets:
                print(f"   失败的桶: {', '.join(failed_buckets)}")
            
            return success_count == len(matching_buckets)
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            print(f"❌ S3 错误 [{error_code}]: {error_msg}")
            return False
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return False
        except Exception as e:
            print(f"❌ 未知错误: {e}")
            return False
    
    def delete_buckets_by_prefix_verbose(self, prefix, confirm=False, dry_run=False):
        """详细格式按前缀批量删除桶"""
        try:
            s3_client = self._get_client()
            
            print("🗑️  批量桶删除详细信息:")
            print("=" * 60)
            print(f"   🏷️  桶名前缀: {prefix}")
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print(f"   ✅ 确认模式: {'是' if confirm else '否'}")
            print(f"   🔍 模拟运行: {'是' if dry_run else '否'}")
            print()
            
            # 列出所有桶
            response = s3_client.list_buckets()
            buckets = response['Buckets']
            
            # 过滤匹配前缀的桶
            matching_buckets = [b['Name'] for b in buckets if b['Name'].startswith(prefix)]
            
            if not matching_buckets:
                print(f"   📭 没有找到前缀为 '{prefix}' 的桶")
                return True
            
            print(f"   🔍 找到 {len(matching_buckets)} 个匹配的桶:")
            for i, bucket_name in enumerate(matching_buckets, 1):
                print(f"      [{i}] {bucket_name}")
            
            if not confirm and not dry_run:
                print(f"\n   ⚠️  这将删除 {len(matching_buckets)} 个桶！")
                print(f"   💡 请使用 --confirm 选项确认删除")
                return False
            
            if dry_run:
                print(f"\n   🔍 模拟运行: 将删除 {len(matching_buckets)} 个桶")
                return True
            
            # 批量删除
            success_count = 0
            failed_buckets = []
            
            print(f"\n   🗑️  开始批量删除:")
            print("   " + "-" * 50)
            
            for i, bucket_name in enumerate(matching_buckets, 1):
                print(f"   [{i}/{len(matching_buckets)}] 删除桶: {bucket_name}")
                
                if self.delete_single_bucket_verbose(bucket_name, force=True):
                    success_count += 1
                    print(f"   ✅ 成功")
                else:
                    failed_buckets.append(bucket_name)
                    print(f"   ❌ 失败")
                print()
            
            # 显示结果
            print("   📊 批量删除统计:")
            print(f"      • 总数量: {len(matching_buckets)}")
            print(f"      • 成功数: {success_count}")
            print(f"      • 失败数: {len(failed_buckets)}")
            print(f"      • 成功率: {(success_count/len(matching_buckets))*100:.1f}%")
            
            if failed_buckets:
                print(f"      • 失败桶列表: {', '.join(failed_buckets)}")
            
            print(f"   📅 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            return success_count == len(matching_buckets)
            
        except Exception as e:
            print(f"   ❌ 错误: {e}")
            return False
    
    def delete_buckets_by_prefix_json(self, prefix, confirm=False, dry_run=False):
        """JSON 格式按前缀批量删除桶"""
        try:
            s3_client = self._get_client()
            
            # 列出所有桶
            response = s3_client.list_buckets()
            buckets = response['Buckets']
            
            # 过滤匹配前缀的桶
            matching_buckets = [b['Name'] for b in buckets if b['Name'].startswith(prefix)]
            
            if not matching_buckets:
                result = {
                    "success": True,
                    "operation": "batch_delete_buckets",
                    "prefix": prefix,
                    "total_count": 0,
                    "message": "没有找到匹配的桶"
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return True
            
            if not confirm and not dry_run:
                result = {
                    "success": False,
                    "operation": "batch_delete_buckets",
                    "prefix": prefix,
                    "total_count": len(matching_buckets),
                    "error": "confirmation_required",
                    "error_message": "请使用 --confirm 选项确认删除",
                    "matching_buckets": matching_buckets
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return False
            
            if dry_run:
                result = {
                    "success": True,
                    "operation": "batch_delete_buckets",
                    "prefix": prefix,
                    "total_count": len(matching_buckets),
                    "mode": "dry_run",
                    "would_delete": True,
                    "matching_buckets": matching_buckets
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return True
            
            # 批量删除
            results = []
            success_count = 0
            
            for bucket_name in matching_buckets:
                try:
                    # 检查桶是否存在
                    try:
                        s3_client.head_bucket(Bucket=bucket_name)
                    except ClientError as e:
                        if e.response['Error']['Code'] == 'NoSuchBucket':
                            results.append({
                                "bucket_name": bucket_name,
                                "success": True,
                                "status": "not_exists",
                                "message": "桶不存在"
                            })
                            success_count += 1
                            continue
                        else:
                            raise
                    
                    # 检查桶是否为空
                    is_empty, message = self._check_bucket_empty(bucket_name)
                    
                    # 如果桶不为空，先清空桶
                    deleted_objects = 0
                    deleted_uploads = 0
                    if not is_empty:
                        success, deleted_objects, deleted_uploads = self._empty_bucket(bucket_name)
                        if not success:
                            results.append({
                                "bucket_name": bucket_name,
                                "success": False,
                                "error": "empty_failed",
                                "error_message": "清空桶失败"
                            })
                            continue
                    
                    # 删除桶
                    s3_client.delete_bucket(Bucket=bucket_name)
                    results.append({
                        "bucket_name": bucket_name,
                        "success": True,
                        "operation": "delete",
                        "deleted_objects": deleted_objects,
                        "deleted_uploads": deleted_uploads
                    })
                    success_count += 1
                    
                except ClientError as e:
                    error_code = e.response['Error']['Code']
                    error_msg = e.response['Error']['Message']
                    results.append({
                        "bucket_name": bucket_name,
                        "success": False,
                        "error": error_code,
                        "error_message": error_msg
                    })
                except Exception as e:
                    results.append({
                        "bucket_name": bucket_name,
                        "success": False,
                        "error": "Unknown",
                        "error_message": str(e)
                    })
            
            # 输出汇总结果
            summary = {
                "success": success_count == len(matching_buckets),
                "operation": "batch_delete_buckets",
                "prefix": prefix,
                "total_count": len(matching_buckets),
                "success_count": success_count,
                "failed_count": len(matching_buckets) - success_count,
                "success_rate": f"{(success_count/len(matching_buckets))*100:.1f}%",
                "results": results,
                "completion_time": datetime.now().isoformat()
            }
            
            print(json.dumps(summary, indent=2, ensure_ascii=False))
            return success_count == len(matching_buckets)
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            error_result = {
                "success": False,
                "error": error_code,
                "error_message": error_msg
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return False
        except NoCredentialsError:
            error_result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据"
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return False
        except Exception as e:
            error_result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e)
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return False


def parse_args():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(
        description='S3 DeleteBucket API 演示工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  %(prog)s --name my-bucket                 # 删除空桶
  %(prog)s --name my-bucket --force         # 强制删除（先清空）
  %(prog)s --prefix temp- --confirm         # 批量删除前缀匹配的桶
  %(prog)s --name my-bucket --dry-run       # 模拟运行
  %(prog)s --format json                    # JSON 格式输出
  %(prog)s --verbose                        # 详细格式输出
  %(prog)s --access-key KEY --secret-key SECRET  # 指定凭据
        """
    )
    
    parser.add_argument(
        '--host',
        default='http://localhost:8000',
        help='S3 服务端点 (默认: http://localhost:8000)'
    )
    
    parser.add_argument(
        '--access-key',
        default='AKIAIOSFODNN7EXAMPLE',
        help='AWS Access Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--secret-key',
        default='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
        help='AWS Secret Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--region',
        default='us-east-1',
        help='AWS 区域 (默认: us-east-1)'
    )
    
    parser.add_argument(
        '--format',
        choices=['simple', 'verbose', 'json'],
        default='simple',
        help='输出格式 (默认: simple)'
    )
    
    parser.add_argument(
        '--verbose',
        action='store_true',
        help='详细输出模式 (等同于 --format verbose)'
    )
    
    # 删除选项
    delete_group = parser.add_mutually_exclusive_group(required=True)
    delete_group.add_argument(
        '--name',
        help='要删除的桶名称'
    )
    
    delete_group.add_argument(
        '--prefix',
        help='要删除的桶名前缀（批量删除）'
    )
    
    parser.add_argument(
        '--force',
        action='store_true',
        help='强制删除（先清空桶内容）'
    )
    
    parser.add_argument(
        '--confirm',
        action='store_true',
        help='确认批量删除操作'
    )
    
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='模拟运行，不实际删除'
    )
    
    return parser.parse_args()


def main():
    """主函数"""
    args = parse_args()
    
    # 如果指定了 --verbose，覆盖 format 设置
    if args.verbose:
        args.format = 'verbose'
    
    # 创建客户端
    client = BucketDeleteClient(
        endpoint_url=args.host,
        access_key=args.access_key,
        secret_key=args.secret_key,
        region=args.region
    )
    
    # 根据格式执行相应操作
    success = False
    
    if args.name:
        if args.format == 'simple':
            success = client.delete_single_bucket_simple(args.name, args.force, args.dry_run)
        elif args.format == 'verbose':
            success = client.delete_single_bucket_verbose(args.name, args.force, args.dry_run)
        elif args.format == 'json':
            success = client.delete_single_bucket_json(args.name, args.force, args.dry_run)
    elif args.prefix:
        if args.format == 'simple':
            success = client.delete_buckets_by_prefix_simple(args.prefix, args.confirm, args.dry_run)
        elif args.format == 'verbose':
            success = client.delete_buckets_by_prefix_verbose(args.prefix, args.confirm, args.dry_run)
        elif args.format == 'json':
            success = client.delete_buckets_by_prefix_json(args.prefix, args.confirm, args.dry_run)
    
    # 设置退出码
    sys.exit(0 if success else 1)


if __name__ == '__main__':
    main()
